import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { Template, DocumentParams } from '@/types';
import * as templateService from '@/services/templateService';

interface TemplateContextType {
  templates: Template[];
  selectedTemplate: Template | null;
  templateParams: DocumentParams;
  documentContent: string;
  isTemplateEditorOpen: boolean;
  isImportTemplateOpen: boolean;
  
  setSelectedTemplate: (template: Template | null) => void;
  updateTemplateParam: (name: string, value: string) => void;
  generateDocument: () => void;
  addTemplate: (template: Omit<Template, 'id'>) => void;
  updateTemplate: (template: Template) => void;
  deleteTemplate: (templateId: string) => void;
  importTemplates: (templatesData: any) => void;
  openTemplateEditor: () => void;
  closeTemplateEditor: () => void;
  openImportTemplate: () => void;
  closeImportTemplate: () => void;
}

const TemplateContext = createContext<TemplateContextType | undefined>(undefined);

export const TemplateProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [templates, setTemplates] = useState<Template[]>([]);
  const [selectedTemplate, setSelectedTemplate] = useState<Template | null>(null);
  const [templateParams, setTemplateParams] = useState<DocumentParams>({});
  const [documentContent, setDocumentContent] = useState('');
  const [isTemplateEditorOpen, setIsTemplateEditorOpen] = useState(false);
  const [isImportTemplateOpen, setIsImportTemplateOpen] = useState(false);
  
  // 加载模板
  useEffect(() => {
    const loadAllTemplates = () => {
      const loadedTemplates = templateService.loadTemplates();
      setTemplates(loadedTemplates);
      if (loadedTemplates.length > 0) {
        setSelectedTemplate(loadedTemplates[0]);
      }
    };
    
    loadAllTemplates();
  }, []);
  
  // 当选择的模板变化时，初始化参数
  useEffect(() => {
    if (selectedTemplate) {
      const initialParams: DocumentParams = {};
      selectedTemplate.params.forEach(param => {
        initialParams[param.name] = '';
      });
      setTemplateParams(initialParams);
      generateDocument();
    }
  }, [selectedTemplate]);
  
  // 当参数变化时更新文档内容
  useEffect(() => {
    if (selectedTemplate) {
      generateDocument();
    }
  }, [templateParams, selectedTemplate]);
  
  // 更新模板参数
  const updateTemplateParam = (name: string, value: string) => {
    setTemplateParams(prev => ({
      ...prev,
      [name]: value
    }));
  };
  
  // 生成文档内容
  const generateDocument = () => {
    if (selectedTemplate) {
      const content = templateService.generateDocumentContent(selectedTemplate, templateParams);
      setDocumentContent(content);
    }
  };
  
  // 添加新模板
  const addTemplate = (template: Omit<Template, 'id'>) => {
    const newTemplate = templateService.addTemplate(template);
    setTemplates(prev => [...prev, newTemplate]);
    setSelectedTemplate(newTemplate);
  };
  
  // 更新模板
  const updateTemplate = (template: Template) => {
    templateService.updateTemplate(template);
    setTemplates(prev => prev.map(t => t.id === template.id ? template : t));
    
    if (selectedTemplate?.id === template.id) {
      setSelectedTemplate(template);
    }
  };
  
  // 删除模板
  const deleteTemplate = (templateId: string) => {
    templateService.deleteTemplate(templateId);
    const updatedTemplates = templates.filter(t => t.id !== templateId);
    setTemplates(updatedTemplates);
    
    if (selectedTemplate?.id === templateId) {
      setSelectedTemplate(updatedTemplates.length > 0 ? updatedTemplates[0] : null);
    }
  };
  
  // 导入模板
  const importTemplates = (templatesData: any) => {
    templateService.importTemplates(templatesData);
    setTemplates(templateService.loadTemplates());
    closeImportTemplate();
  };
  
  // 打开/关闭模板编辑器
  const openTemplateEditor = () => setIsTemplateEditorOpen(true);
  const closeTemplateEditor = () => setIsTemplateEditorOpen(false);
  
  // 打开/关闭导入模板对话框
  const openImportTemplate = () => setIsImportTemplateOpen(true);
  const closeImportTemplate = () => setIsImportTemplateOpen(false);
  
  return (
    <TemplateContext.Provider value={{
      templates,
      selectedTemplate,
      templateParams,
      documentContent,
      isTemplateEditorOpen,
      isImportTemplateOpen,
      
      setSelectedTemplate,
      updateTemplateParam,
      generateDocument,
      addTemplate,
      updateTemplate,
      deleteTemplate,
      importTemplates,
      openTemplateEditor,
      closeTemplateEditor,
      openImportTemplate,
      closeImportTemplate
    }}>
      {children}
    </TemplateContext.Provider>
  );
};

export const useTemplateContext = () => {
  const context = useContext(TemplateContext);
  if (context === undefined) {
    throw new Error('useTemplateContext must be used within a TemplateProvider');
  }
  return context;
};